/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package reportcenter.datasource.ui;

import java.util.List;
import javax.swing.JTable;
import javax.swing.table.TableColumnModel;
import org.springframework.context.ApplicationEvent;
import org.springframework.richclient.application.event.LifecycleApplicationEvent;
import org.springframework.richclient.table.support.AbstractObjectTable;
import reportcenter.datasource.business.DataSourceDao;
import reportcenter.datasource.dominio.DataSource;

/**
 *
 * @author renan
 */
public class DataSourceTable extends AbstractObjectTable{
    
    private DataSourceDao dao;
    
    public DataSourceTable(DataSourceDao dao){
//        super("dataSources", new String[]{"Nome da Conexão","Driver JDBC","Usuário do Schema"});
        super("dataSources", new String[]{"name","driver","usu"});
        this.dao = dao;
    }
    
    public void refreshTable(){
        List list = getBaseEventList();
        list.clear();
        list.addAll(dao.getAll());
    }

    @Override
    protected Object[] getDefaultInitialData() {
        return dao.getAll().toArray();
    }
    
    protected void configureTable(JTable table){
        TableColumnModel tcm = table.getColumnModel();
        //NAME, DRIVER, USU
        tcm.getColumn(0).setPreferredWidth(80);
        tcm.getColumn(1).setPreferredWidth(120);
        tcm.getColumn(2).setPreferredWidth(50);
        
    }
    
    public DataSource[] getSelectedDataSources(){
        int[] selected = getTable().getSelectedRows();
        DataSource[] dataSources = new DataSource[selected.length];
        for (int i = 0; i < selected.length; i++) {
            dataSources[i] = (DataSource) getTableModel().getElementAt(selected[i]);
        }
        return dataSources;
    }
    
    public DataSource getSelectedDataSource(){
        return (DataSource) getSelectedDataSources()[0];
    }
    
    @Override
	protected boolean shouldHandleEvent(ApplicationEvent event) {
		if (event instanceof LifecycleApplicationEvent) {
			Class<? extends Object> eventClass = (((LifecycleApplicationEvent) event).getObject().getClass());
			return getTableObjectsClass().isAssignableFrom(eventClass) && super.shouldHandleEvent(event);
		} else {
			return super.shouldHandleEvent(event);
					}
	}

    public Class<? extends Object> getTableObjectsClass() {
        return DataSource.class;
    }
}